package cc.vv.baselibrary.util.remind;

import android.annotation.SuppressLint;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.text.TextUtils;
import android.util.Log;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

import cc.vv.baselibrary.db.daTable.RemindFunctionObj;
import cc.vv.baselibrary.util.BaseTimeUtil;
import cc.vv.baselibrary.util.LKLogUtil;
import cc.vv.baselibrary.util.LKToastUtil;
import cc.vv.lkbasecomponent.base.app.LKBaseApplication;

/**
 * 系统闹钟工具类
 * Created by sun.li on 2017/9/15.
 */

public class BCAlarmUtil {

    /**
     * 设置系统闹钟
     */
    @SuppressLint("SimpleDateFormat")
    public static void setSystemAlarm(Context mContext, RemindFunctionObj obj, long repeatTime) {
        Log.d("lx_log", "setSystemAlarm: 设置闹钟....." + obj.toString());
        mContext = LKBaseApplication.getApplication().getApplicationContext();
        if (mContext != null) {
            AlarmManager alarmManager = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
            if (alarmManager != null && obj != null) {
                //操作：发送一个广播，广播接收后Toast提示定时操作完成
                Intent intent = new Intent(mContext, MyAlarmReceiver.class);
                intent.setAction("cc.vv.btpartyjob.MyAlarm");
                /*提醒唯一标志ID*/
                String remindUUID = obj.getAlarmID();
                if (remindUUID == null || TextUtils.isEmpty(remindUUID)) {
                    remindUUID = obj.getRemindID() + obj.getRemindTitle() + obj.getRemindStartTime() + obj.getRemindTitle() + obj.getRemindRepetitionDate();
                }
                //此处设置用于区分不同的Intent，区别闹钟；
                String uri = "content://calendar/calendar_alerts/" + remindUUID;
                intent.setData(Uri.parse(uri));
                intent.putExtra("Remind", obj);
                //PendingIntent 的 requestCode值相同时会覆盖之前的intent, 每一个闹钟对应一个不同的code, 保证多个闹钟不会被覆盖
                PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, obj.getCode(), intent, PendingIntent.FLAG_CANCEL_CURRENT);
                if (!TextUtils.isEmpty(obj.getRemindEndDate())) {
                    try {
                        if (new SimpleDateFormat("yyyy.MM.dd").parse(obj.getRemindEndDate()).getTime() < new Date().getTime()) {
                            Log.d("lx_log", "setSystemAlarm: 设置结束时间小于当前时间, 不设置闹钟提醒...");
                            return;
                        }
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }
                if (!TextUtils.isEmpty(obj.getRemindRepetitionDate())) {
                    if (!obj.getRemindRepetitionDate().contains("每天") && !obj.getRemindRepetitionDate().contains(BaseTimeUtil.getWeek(new Date().getTime()))) {
                        Log.d("lx_log", "setSystemAlarm: 重复设置不符合规定...");
                        return;
                    }
                }
                try {
                    //闹钟提醒时间
                    String time = "08:00";
                    if (!TextUtils.isEmpty(obj.getRemindStartTime())) {
                        time = obj.getRemindStartTime();
                    }
                    String[] times = time.split(":");
                    Calendar instance = Calendar.getInstance();
                    instance.setTimeInMillis(System.currentTimeMillis());
                    instance.setTimeZone(TimeZone.getTimeZone("GMT+8"));
                    instance.set(Calendar.HOUR_OF_DAY, Integer.parseInt(times[0]));
                    instance.set(Calendar.MINUTE, Integer.parseInt(times[1]));
                    instance.set(Calendar.SECOND, 0);
                    if (repeatTime > 0) {
                        //当repeatTime > 0 时,此时闹钟设置为重复闹钟,使用当前时间+延时
                        setAlarm(alarmManager, System.currentTimeMillis() + repeatTime, pendingIntent);
                        Log.d("lx_log", "设置稍后闹钟提醒成功..." + (System.currentTimeMillis() + repeatTime));
                    } else {
                        //设置时间小于当前时间, 设置第二天闹钟
                        if (System.currentTimeMillis() - instance.getTimeInMillis() > 0) {
                            //设置日期+1
                            instance.add(Calendar.DAY_OF_MONTH, 1);
                            Log.d("lx_log", "设置闹钟提醒天数 +1");
                        }
                        setAlarm(alarmManager, instance.getTimeInMillis(), pendingIntent);
                        Log.d("lx_log", "设置闹钟提醒成功..." + instance.getTimeInMillis());
                    }
                } catch (Exception e) {
                    LKToastUtil.showToastShort("定时提醒失败,请重新设置");
                }
            }
        }
    }

    /**
     * 设置广播
     *
     * @param alarmManager
     * @param triggerAtMillis
     * @param pendingIntent
     */

    private static void setAlarm(AlarmManager alarmManager, long triggerAtMillis, PendingIntent pendingIntent) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, triggerAtMillis, pendingIntent);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            alarmManager.setWindow(AlarmManager.RTC_WAKEUP, triggerAtMillis, triggerAtMillis, pendingIntent);
        } else {
            alarmManager.set(AlarmManager.RTC_WAKEUP, triggerAtMillis, pendingIntent);
        }
    }

    /**
     * 删除系统闹钟
     */
    public static void cancelSystemAlarm(Context mContext, RemindFunctionObj obj) {
        Log.d("lx_log", "cancelSystemAlarm: 关闭闹钟啦......");
        if (mContext != null) {
            AlarmManager alarmManager = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
            if (alarmManager != null && obj != null) {
                //操作：发送一个广播，广播接收后Toast提示定时操作完成
                Intent intent = new Intent(mContext, MyAlarmReceiver.class);
                intent.setAction("cc.vv.btpartyjob.MyAlarm");
                /*提醒唯一标志ID*/
                String remindUUID = obj.getAlarmID();
                if (remindUUID == null || TextUtils.isEmpty(remindUUID)) {
                    remindUUID = obj.getRemindID() + obj.getRemindTitle() + obj.getRemindStartTime() + obj.getRemindTitle() + obj.getRemindRepetitionDate();
                }
                String uri = "content://calendar/calendar_alerts/" + remindUUID;
                LKLogUtil.e(uri);
                intent.setData(Uri.parse(uri));//此处设置用于区分不同的Intent，区别闹钟；
                intent.putExtra("RemindID", obj.getRemindID());
//                intent.putExtra("Title", obj.getRemindTitle()+"_"+obj.getRemindStartTime());
//                intent.putExtra("StartTime", obj.getRemindStartTime());
                intent.putExtra(String.valueOf(obj.getRemindID()), obj.getRemindID());
                PendingIntent pendingIntent =
                        PendingIntent.getBroadcast(mContext, 0, intent, 0);
                alarmManager.cancel(pendingIntent);
            }
        }
    }
}
